package grpc

import (
	"context"
	"gitlab.local/backend/proto/base"
	"gitlab.local/backend/proto/dto"
	"simcard/bll"
	"simcard/model"
	"simcard/utils"
	"time"
)

type SimCard struct {
}

// GetDataBalance 查询流量卡的非实时的剩余流量
func (s *SimCard) GetDataBalance(ctx context.Context, req *dto.SimReq, resp *dto.SimDataBalanceResp) error {

	return nil
}

// GetSimCardInfo 查询流量卡的非实时详细数据
func (s *SimCard) GetSimCardInfo(ctx context.Context, req *dto.SimReq, resp *dto.GetSimCardInfoResp) error {

	return nil
}

// Recharge 流量卡充值
func (s *SimCard) Recharge(ctx context.Context, req *dto.SimReq, resp *dto.GetSimCardInfoResp) error {

	return nil
}

// Recharge 流量卡充值
func (s *SimCard) Sync(ctx context.Context, req *dto.SyncSimReq, resp *base.Empty) error {

	var (
		upsertes    []*model.SimCardUpsertRequest
		delEbikeIds []int64
	)

	ctx, _ = context.WithTimeout(context.Background(), time.Minute*3)
	for _, v := range req.SimInfo {
		if v.OpType == dto.SyncSimOpType_Delete {
			delEbikeIds = append(delEbikeIds, v.EbikeId)
		} else {
			upsertes = append(upsertes, &model.SimCardUpsertRequest{
				EbikeId:   v.EbikeId,
				UserId:    v.UserId,
				UserPhone: v.UserPhone,
				Sn:        v.SnCode,
				FrameCode: v.FrameCode,
				Iccid:     v.Iccid,
			})
		}
	}

	if len(delEbikeIds) > 0 {
		for _, u := range utils.SplitSlice(delEbikeIds, 20) {
			return bll.SimCard.Delete(ctx, &model.SimCardDeleteRequest{
				EbikeIds: u,
			})
		}
	}

	syncRequest := &model.SyncRequest{
		Data:      upsertes,
		DataType:  model.DataFetchTypePush,
		DataRange: model.SimCardSyncDataPartOf,
	}

	resp = &base.Empty{}
	return bll.SimCard.Sync(ctx, syncRequest)
}

// 服务费预充
func (s *SimCard) CreatePrepaid(ctx context.Context, req *dto.CreatePrepaidReq, resp *base.Empty) error {

	resp = &base.Empty{}
	return bll.Prepaid.Create(ctx, &model.PrepaidCreateRequest{
		PaymentId: req.PaymentId,
		EbikeId:   req.EbikeId,
		Sn:        req.Sn,
		Source:    int(req.Source),
		Years:     int(req.Years),
	})
}
